package com.yt.user.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yt.common.utils.Md5Utils;
import com.yt.user.models.dto.SysUserDTO;
import com.yt.user.models.service.ISysUserService;
import com.yt.user.models.vo.LoginInfoVO;
import com.yt.user.models.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.user.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.user.mapper.LoginInfoMapper;
import com.yt.user.models.service.ILoginInfoService;
import com.yt.user.models.bo.LoginInfoSaveBO;
import com.yt.user.models.dto.LoginInfoDTO;

/**
 * 登录信息控制器
 *
 * @author zhao
 * @Date 2025-09-03 16:13:38
 */
@DubboService
@Slf4j
public class LoginInfoServiceImpl extends ServiceImpl<LoginInfoMapper, LoginInfoDTO> implements ILoginInfoService{

    @Resource
    private YmlConfig ymlConfig;

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private ILoginInfoService loginInfoService;

    @Override
    public boolean add(LoginInfoSaveBO saveBO) {
        LoginInfoDTO dto = new LoginInfoDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    @Override
    public LoginInfoVO getLogin(LoginInfoSaveBO saveBO) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("account",saveBO.getAccount());
        LoginInfoDTO loginInfoDTO = this.selectOne(wrapper);
        if(null != loginInfoDTO){
            LoginInfoVO loginInfoVO = new LoginInfoVO();
            BeanUtils.copyProperties(loginInfoDTO,loginInfoVO);
            return loginInfoVO;
        }
        return null;
    }

    @Override
    public SysUserVO getUserLogin(LoginInfoSaveBO saveBO) {
        LoginInfoVO loginInfoVO = getLogin(saveBO);
        if(null == loginInfoVO){
            return null;
        }

        SysUserVO sysUserVO =  new SysUserVO();
        //获取用户信息
        SysUserDTO sysUserDTO = iSysUserService.selectById(loginInfoVO.getUserId());
        //校验密码
        String password = saveBO.getPassword();
        String salt = loginInfoVO.getSalt();
        String md5Password = Md5Utils.MD5Encode(password,salt);
        log.info("loginInfoVO.getPassword()={} , MD5Encode password:{}",md5Password,Md5Utils.MD5Encode(saveBO.getPassword(),loginInfoVO.getSalt()));
        if(md5Password.equals(Md5Utils.MD5Encode(saveBO.getPassword(),loginInfoVO.getSalt()))){
            //密码校验成功，返回用户信息
            BeanUtils.copyProperties(sysUserDTO,sysUserVO);
            return sysUserVO;
        }
        return null;
    }
}
